<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<!DOCTYPE html>
<html>
<head>
    <title>管理管理员</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#f97316',
                        admin: '#6366f1',
                        neutral: {
                            100: '#f3f4f6',
                            200: '#e5e7eb',
                            700: '#374151',
                            800: '#1f2937',
                            900: '#111827'
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-0.5;
            }
            .form-input-focus {
                @apply focus:ring-2 focus:ring-admin/50 focus:border-admin;
            }
            .nav-active {
                @apply text-primary border-b-2 border-admin pb-0.5 font-medium;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 导航栏 -->
<nav class="bg-white shadow-md sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-6">
            <a href="<%= request.getContextPath() %>/cjj/admin_dashboard.jsp" class="text-primary font-medium flex items-center">
                <i class="fa fa-tachometer mr-2"></i> 管理后台
            </a>
            <a href="<%= request.getContextPath() %>/cjj/admin_dashboard.jsp" class="text-neutral-700 hover:text-primary transition-colors ${activePage == 'dashboard' ? 'nav-active' : ''}">
                <i class="fa fa-home mr-1"></i> 首页
            </a>
            <div class="relative group ${activePage == 'movies' ? '' : (activePage == 'books' ? '' : '')}">
                <a href="#" class="nav-link text-neutral-700 hover:text-primary transition-colors flex items-center" data-page="movies">
                    <i class="fa fa-film mr-1"></i> 电影管理 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </a>
                <div id="movieDropdown" class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 hidden group-hover:block pointer-events-auto">
                    <a href="<%= request.getContextPath() %>/cjj/publish_movie.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-movie hover:text-white">发布电影</a>
                    <a href="<%= request.getContextPath() %>/cjj/manage_movies.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-movie hover:text-white">管理电影</a>
                </div>
            </div>
            <div class="relative group ${activePage == 'books' ? '' : ''}">
                <a href="#" class="nav-link text-neutral-700 hover:text-primary transition-colors flex items-center" data-page="books">
                    <i class="fa fa-book mr-1"></i> 图书管理 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </a>
                <div id="bookDropdown" class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 hidden group-hover:block pointer-events-auto">
                    <a href="<%= request.getContextPath() %>/cjj/publish_book.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-book hover:text-white">发布图书</a>
                    <a href="<%= request.getContextPath() %>/cjj/manage_books.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-book hover:text-white">管理图书</a>
                </div>
            </div>
            <a href="<%= request.getContextPath() %>/cjj/manage_admins.jsp" class="text-primary border-b-2 border-admin pb-0.5 font-medium flex items-center ${activePage == 'admins' ? 'nav-active' : ''}">
                <i class="fa fa-users mr-1"></i> 管理管理员
            </a>
        </div>
        <div class="flex items-center space-x-4">
                <span class="text-neutral-700">
                    <i class="fa fa-user-circle mr-1"></i>
                    <%= (String)request.getSession().getAttribute("adminUsername") != null
                            ? (String)request.getSession().getAttribute("adminUsername") : "管理员" %>
                </span>
            <a href="<%= request.getContextPath() %>/admin/logout" class="text-neutral-700 hover:text-red-500 transition-colors">
                <i class="fa fa-sign-out mr-1"></i> 退出
            </a>
        </div>
    </div>
</nav>

<!-- 主内容区 -->
<main class="container mx-auto px-4 py-8">
    <!-- 页面标题 -->
    <div class="bg-gradient-to-r from-admin/10 to-admin/5 rounded-xl p-6 mb-8">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-800">管理管理员</h1>
        <p class="text-neutral-600 mt-2">查看和管理所有管理员账户</p>
    </div>

    <!-- 操作结果提示 -->
    <%
        String message = (String) request.getAttribute("message");
        boolean success = request.getAttribute("success") != null &&
                (Boolean) request.getAttribute("success");
        if (message != null) {
    %>
    <div class="mb-4 px-4 py-3 rounded-lg
        <%= success ? "bg-green-50 border border-green-200 text-green-700" :
                      "bg-red-50 border border-red-200 text-red-700" %>">
        <div class="flex items-center">
            <i class="fa fa-<%= success ? "check-circle" : "exclamation-circle" %> mr-2"></i>
            <span><%= message %></span>
        </div>
    </div>
    <%
        }
    %>

    <!-- 管理员表格 -->
    <div class="bg-white rounded-xl p-6 card-shadow mb-8">
        <div class="flex justify-end mb-4">
            <button id="addAdminBtn" class="px-5 py-2.5 bg-admin text-white rounded-lg hover:bg-admin/90 transition-colors btn-hover">
                <i class="fa fa-plus-circle mr-2"></i> 添加管理员
            </button>
        </div>

        <!-- 管理员表格 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-neutral-200">
                <thead class="bg-neutral-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">ID</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">用户名</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">邮箱</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">创建时间</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                </tr>
                </thead>
                <tbody class="bg-white divide-y divide-neutral-200">
                <%
                    // 处理删除操作
                    String action = request.getParameter("action");
                    if ("delete".equals(action) && request.getParameter("id") != null) { // 使用id而非admin_id
                        try {
                            Integer adminId = Integer.valueOf(request.getParameter("id"));
                            // 超级管理员(ID=1)不允许删除
                            if (adminId == 1) {
                                request.setAttribute("message", "超级管理员不允许删除");
                                request.setAttribute("success", false);
                            } else {
                                Connection conn = null;
                                PreparedStatement stmt = null;

                                try {
                                    // 加载数据库驱动
                                    Class.forName("com.mysql.cj.jdbc.Driver");
                                    // 建立数据库连接
                                    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");

                                    // 执行删除操作，表字段为id
                                    String sql = "DELETE FROM admin WHERE id = ?";
                                    stmt = conn.prepareStatement(sql);
                                    stmt.setInt(1, adminId);
                                    int rows = stmt.executeUpdate();

                                    if (rows > 0) {
                                        request.setAttribute("message", "管理员删除成功");
                                        request.setAttribute("success", true);
                                    } else {
                                        request.setAttribute("message", "未找到指定管理员");
                                        request.setAttribute("success", false);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    request.setAttribute("message", "删除管理员失败: " + e.getMessage());
                                    request.setAttribute("success", false);
                                } finally {
                                    // 关闭资源
                                    if (stmt != null) try { stmt.close(); } catch (SQLException e) {}
                                    if (conn != null) try { conn.close(); } catch (SQLException e) {}
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            request.setAttribute("message", "参数错误: " + e.getMessage());
                            request.setAttribute("success", false);
                        }
                    }

                    // 处理编辑操作
                    if ("edit".equals(action) && request.getParameter("id") != null) { // 使用id而非admin_id
                        try {
                            Integer adminId = Integer.valueOf(request.getParameter("id"));
                            String username = request.getParameter("username");
                            String email = request.getParameter("email");
                            String password = request.getParameter("password");

                            Connection conn = null;
                            PreparedStatement stmt = null;

                            try {
                                // 加载数据库驱动
                                Class.forName("com.mysql.cj.jdbc.Driver");
                                // 建立数据库连接
                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");

                                // 构建更新SQL
                                StringBuilder sqlBuilder = new StringBuilder("UPDATE admin SET ");
                                List<String> params = new ArrayList<>();

                                if (username != null && !username.isEmpty()) {
                                    sqlBuilder.append("username = ?, ");
                                    params.add(username);
                                }
                                if (email != null && !email.isEmpty()) {
                                    sqlBuilder.append("email = ?, ");
                                    params.add(email);
                                }
                                if (password != null && !password.isEmpty()) {
                                    sqlBuilder.append("password = ?, ");
                                    params.add(password);
                                }

                                // 移除最后的逗号和空格
                                if (sqlBuilder.toString().endsWith(", ")) {
                                    sqlBuilder.setLength(sqlBuilder.length() - 2);
                                }

                                sqlBuilder.append(" WHERE id = ?");
                                params.add(adminId.toString());

                                String sql = sqlBuilder.toString();
                                stmt = conn.prepareStatement(sql);

                                // 设置参数
                                for (int i = 0; i < params.size(); i++) {
                                    stmt.setString(i + 1, params.get(i));
                                }

                                int rows = stmt.executeUpdate();

                                if (rows > 0) {
                                    request.setAttribute("message", "管理员信息更新成功");
                                    request.setAttribute("success", true);
                                } else {
                                    request.setAttribute("message", "未找到指定管理员");
                                    request.setAttribute("success", false);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                request.setAttribute("message", "更新管理员失败: " + e.getMessage());
                                request.setAttribute("success", false);
                            } finally {
                                // 关闭资源
                                if (stmt != null) try { stmt.close(); } catch (SQLException e) {}
                                if (conn != null) try { conn.close(); } catch (SQLException e) {}
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            request.setAttribute("message", "参数错误: " + e.getMessage());
                            request.setAttribute("success", false);
                        }
                    }

                    // 处理添加操作（通过表单提交）
                    if ("add".equals(action)) {
                        try {
                            String username = request.getParameter("username");
                            String email = request.getParameter("email");
                            String password = request.getParameter("password");
                            String confirmPassword = request.getParameter("confirmPassword");

                            // 表单验证
                            if (username == null || username.isEmpty() ||
                                    email == null || email.isEmpty() ||
                                    password == null || password.isEmpty() ||
                                    confirmPassword == null || !password.equals(confirmPassword)) {
                                request.setAttribute("message", "请填写完整且一致的表单信息");
                                request.setAttribute("success", false);
                            } else {
                                Connection conn = null;
                                PreparedStatement stmt = null;
                                ResultSet rs = null;

                                try {
                                    // 加载数据库驱动
                                    Class.forName("com.mysql.cj.jdbc.Driver");
                                    // 建立数据库连接
                                    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");

                                    // 检查用户名是否已存在
                                    String checkSql = "SELECT id FROM admin WHERE username = ?";
                                    stmt = conn.prepareStatement(checkSql);
                                    stmt.setString(1, username);
                                    rs = stmt.executeQuery();

                                    if (rs.next()) {
                                        request.setAttribute("message", "用户名已存在，请更换用户名");
                                        request.setAttribute("success", false);
                                    } else {
                                        // 实际项目中应使用加密算法(如BCrypt)
                                        String sql = "INSERT INTO admin (username, password, email, created_at) " +
                                                "VALUES (?, ?, ?, NOW())";
                                        stmt = conn.prepareStatement(sql);
                                        stmt.setString(1, username);
                                        stmt.setString(2, password); // 实际项目中应加密
                                        stmt.setString(3, email);

                                        int rows = stmt.executeUpdate();

                                        if (rows > 0) {
                                            request.setAttribute("message", "管理员添加成功");
                                            request.setAttribute("success", true);
                                        } else {
                                            request.setAttribute("message", "管理员添加失败");
                                            request.setAttribute("success", false);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    request.setAttribute("message", "添加管理员失败: " + e.getMessage());
                                    request.setAttribute("success", false);
                                } finally {
                                    // 关闭资源
                                    if (rs != null) try { rs.close(); } catch (SQLException e) {}
                                    if (stmt != null) try { stmt.close(); } catch (SQLException e) {}
                                    if (conn != null) try { conn.close(); } catch (SQLException e) {}
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            request.setAttribute("message", "添加管理员时发生错误: " + e.getMessage());
                            request.setAttribute("success", false);
                        }
                    }

                    // 查询管理员列表，表字段为id
                    List<Map<String, Object>> admins = new ArrayList<>();
                    Connection conn = null;
                    Statement stmt = null;
                    ResultSet rs = null;

                    try {
                        // 加载数据库驱动
                        Class.forName("com.mysql.cj.jdbc.Driver");
                        // 建立数据库连接
                        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");
                        stmt = conn.createStatement();
                        rs = stmt.executeQuery("SELECT id, username, email, created_at FROM admin"); // 查询字段为id

                        while (rs.next()) {
                            Map<String, Object> admin = new HashMap<>();
                            admin.put("id", rs.getInt("id"));
                            admin.put("username", rs.getString("username"));
                            admin.put("email", rs.getString("email"));
                            admin.put("createdAt", rs.getTimestamp("created_at"));
                            admins.add(admin);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                %>
                <tr>
                    <td colspan="5" class="px-6 py-4 text-center text-red-500">
                        数据库查询失败: <%= e.getMessage() %>
                    </td>
                </tr>
                <%
                    } finally {
                        // 关闭资源
                        if (rs != null) try { rs.close(); } catch (SQLException e) {}
                        if (stmt != null) try { stmt.close(); } catch (SQLException e) {}
                        if (conn != null) try { conn.close(); } catch (SQLException e) {}
                    }

                    // 动态生成表格行
                    if (admins.isEmpty()) {
                %>
                <tr>
                    <td colspan="5" class="px-6 py-4 text-center text-neutral-500">
                        没有找到管理员记录
                    </td>
                </tr>
                <%
                } else {
                    for (Map<String, Object> admin : admins) {
                        Integer adminId = (Integer) admin.get("id");
                %>
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-500"><%= adminId %></td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10 rounded-full bg-admin/10 flex items-center justify-center">
                                <i class="fa fa-user text-admin"></i>
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-neutral-900"><%= admin.get("username") %></div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 text-sm text-neutral-700"><%= admin.get("email") %></td>
                    <td class="px-6 py-4 text-sm text-neutral-700"><%= new SimpleDateFormat("yyyy-MM-dd").format(admin.get("createdAt")) %></td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button onclick="editAdmin(
                            <%= adminId %>,
                                '<%= admin.get("username") != null ? ((String) admin.get("username")).replace("'", "\\'") : "" %>',
                                '<%= admin.get("email") != null ? ((String) admin.get("email")).replace("'", "\\'") : "" %>'
                                )" class="text-primary hover:text-primary/80 mr-3">编辑</button>
                        <button onclick="deleteAdmin(<%= adminId %>)" class="text-red-500 hover:text-red-600 <%= adminId == 1 ? "opacity-50 cursor-not-allowed" : "" %>" <%= adminId == 1 ? "disabled" : "" %>>删除</button>
                    </td>
                </tr>
                <%
                        }
                    }
                %>
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-6">
            <div class="text-sm text-neutral-500">
                显示 1 到 <%= admins.size() %> 条，共 <%= admins.size() %> 条记录
            </div>
            <div class="flex space-x-2">
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">上一页</a>
                <a href="#" class="px-3 py-1 bg-admin text-white rounded-md hover:bg-admin/90">1</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">2</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">3</a>
                <span class="px-3 py-1 text-neutral-500">...</span>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">12</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">下一页</a>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-neutral-200 py-6">
    <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="text-neutral-600 text-sm mb-4 md:mb-0">
                © 2025 影视图书管理系统. 保留所有权利.
            </div>
            <div class="flex space-x-4">
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-question-circle mr-1"></i> 帮助中心
                </a>
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-envelope mr-1"></i> 联系我们
                </a>
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-file-text-o mr-1"></i> 使用条款
                </a>
            </div>
        </div>
    </div>
</footer>

<!-- 添加管理员模态框 -->
<div id="addAdminModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-neutral-800">添加管理员</h3>
            <button onclick="closeAddModal()" class="text-neutral-400 hover:text-neutral-600">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <form id="addAdminForm" method="post" action="<%= request.getContextPath() %>/cjj/manage_admins.jsp">
            <input type="hidden" name="action" value="add">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="addUsername" class="block text-sm font-medium text-neutral-700 mb-1">用户名 <span class="text-red-500">*</span></label>
                    <input type="text" id="addUsername" name="username" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="addEmail" class="block text-sm font-medium text-neutral-700 mb-1">邮箱 <span class="text-red-500">*</span></label>
                    <input type="email" id="addEmail" name="email" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="addPassword" class="block text-sm font-medium text-neutral-700 mb-1">密码 <span class="text-red-500">*</span></label>
                    <input type="password" id="addPassword" name="password" minlength="6" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="addConfirmPassword" class="block text-sm font-medium text-neutral-700 mb-1">确认密码 <span class="text-red-500">*</span></label>
                    <input type="password" id="addConfirmPassword" name="confirmPassword" minlength="6" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
            </div>
            <div class="mt-6 flex justify-end space-x-3">
                <button type="button" onclick="closeAddModal()" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-50 transition-colors">取消</button>
                <button type="submit" class="px-5 py-2.5 bg-admin text-white rounded-lg hover:bg-admin/90 transition-colors btn-hover">添加</button>
            </div>
        </form>
    </div>
</div>

<!-- 编辑管理员模态框 -->
<div id="editAdminModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-neutral-800">编辑管理员</h3>
            <button onclick="closeEditModal()" class="text-neutral-400 hover:text-neutral-600">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <form id="editAdminForm" method="post" action="<%= request.getContextPath() %>/cjj/manage_admins.jsp">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" id="editAdminId" name="id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="editUsername" class="block text-sm font-medium text-neutral-700 mb-1">用户名</label>
                    <input type="text" id="editUsername" name="username" class="w-full px-4 py-2 border border-neutral-300 rounded-lg bg-neutral-50" readonly>
                </div>
                <div>
                    <label for="editEmail" class="block text-sm font-medium text-neutral-700 mb-1">邮箱</label>
                    <input type="email" id="editEmail" name="email" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="editPassword" class="block text-sm font-medium text-neutral-700 mb-1">新密码 (留空表示不修改)</label>
                    <input type="password" id="editPassword" name="password" minlength="6" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" placeholder="输入新密码">
                </div>
                <div></div> <!-- 空单元格保持布局一致 -->
            </div>
            <div class="mt-6 flex justify-end space-x-3">
                <button type="button" onclick="closeEditModal()" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-50 transition-colors">取消</button>
                <button type="submit" class="px-5 py-2.5 bg-admin text-white rounded-lg hover:bg-admin/90 transition-colors btn-hover">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 删除管理员确认模态框 -->
<div id="deleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <div class="text-center mb-4">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 text-red-500 mb-4">
                <i class="fa fa-trash-o text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-neutral-800">确认删除</h3>
            <p class="text-neutral-600 mt-2">确定要删除这个管理员账户吗？此操作不可撤销。</p>
            <input type="hidden" id="deleteAdminId" name="id">
            <p class="text-sm text-red-500 mt-2" id="deleteAdminUsername"></p>
        </div>
        <div class="flex justify-center space-x-3 mt-6">
            <button onclick="closeDeleteModal()" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-50 transition-colors">取消</button>
            <button onclick="confirmDeleteAdmin()" class="px-5 py-2.5 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors btn-hover">确认删除</button>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>
    // 转义JavaScript字符串，防止引号问题
    function escapeJsString(str) {
        if (!str) return '';
        return str
            .replace(/\\/g, '\\\\')
            .replace(/'/g, '\\\'')
            .replace(/"/g, '\\"')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\t/g, '\\t');
    }

    document.addEventListener('DOMContentLoaded', function() {
        console.log('Manage Admins Page Loaded');
        // 设置当前页面为管理员管理
        const activeNavLink = document.querySelector('[data-page="admins"]');
        if (activeNavLink) {
            activeNavLink.parentElement.classList.add('nav-active');
        }

        // 导航栏下拉菜单优化
        const movieDropdown = document.getElementById('movieDropdown');
        const bookDropdown = document.getElementById('bookDropdown');
        const movieMenu = movieDropdown.parentElement;
        const bookMenu = bookDropdown.parentElement;

        // 鼠标离开菜单时添加延迟消失效果
        let hideTimeout;
        const dropdowns = [
            { menu: movieMenu, dropdown: movieDropdown },
            { menu: bookMenu, dropdown: bookDropdown }
        ];

        dropdowns.forEach(item => {
            const { menu, dropdown } = item;

            // 鼠标进入菜单或下拉框时显示下拉框
            menu.addEventListener('mouseenter', () => {
                clearTimeout(hideTimeout);
                dropdown.classList.remove('hidden');
            });

            // 鼠标离开菜单时延迟隐藏下拉框
            menu.addEventListener('mouseleave', () => {
                hideTimeout = setTimeout(() => {
                    dropdown.classList.add('hidden');
                }, 200);
            });

            // 鼠标进入下拉框时取消隐藏延迟
            dropdown.addEventListener('mouseenter', () => {
                clearTimeout(hideTimeout);
            });

            // 鼠标离开下拉框时重新设置隐藏延迟
            dropdown.addEventListener('mouseleave', () => {
                hideTimeout = setTimeout(() => {
                    dropdown.classList.add('hidden');
                }, 200);
            });
        });

        // 添加管理员按钮点击事件
        const addAdminBtn = document.getElementById('addAdminBtn');
        if (addAdminBtn) {
            addAdminBtn.addEventListener('click', function() {
                document.getElementById('addUsername').value = '';
                document.getElementById('addEmail').value = '';
                document.getElementById('addPassword').value = '';
                document.getElementById('addConfirmPassword').value = '';
                document.getElementById('addAdminModal').classList.remove('hidden');
            });
        } else {
            console.error('添加管理员按钮未找到');
        }

        // 添加管理员表单提交验证
        const addAdminForm = document.getElementById('addAdminForm');
        if (addAdminForm) {
            addAdminForm.addEventListener('submit', function(e) {
                const password = document.getElementById('addPassword').value;
                const confirmPassword = document.getElementById('addConfirmPassword').value;

                if (password !== confirmPassword) {
                    e.preventDefault();
                    showNotification('error', '两次输入的密码不一致');
                }
            });
        }
    });

    // 当前要删除的管理员ID
    let currentAdminId = null;

    // 编辑管理员
    function editAdmin(id, username, email) {
        document.getElementById('editAdminId').value = id;
        document.getElementById('editUsername').value = username;
        document.getElementById('editEmail').value = email;
        document.getElementById('editPassword').value = '';

        document.getElementById('editAdminModal').classList.remove('hidden');
    }

    // 关闭编辑模态框
    function closeEditModal() {
        document.getElementById('editAdminModal').classList.add('hidden');
        document.getElementById('editAdminForm').reset();
    }

    // 删除管理员
    function deleteAdmin(id) {
        // 超级管理员不允许删除
        if (id === 1) {
            alert('超级管理员不允许删除');
            return;
        }

        currentAdminId = id;

        // 使用更可靠的方式获取管理员行
        const adminRows = document.querySelectorAll('table tbody tr');
        for (let i = 0; i < adminRows.length; i++) {
            const row = adminRows[i];
            const firstCell = row.querySelector('td:first-child');
            if (firstCell && firstCell.textContent.trim() === id.toString()) {
                const username = row.querySelector('.text-neutral-900').textContent;

                document.getElementById('deleteAdminId').value = id;
                document.getElementById('deleteAdminUsername').textContent = '即将删除管理员: ' + username;
                document.getElementById('deleteModal').classList.remove('hidden');
                return;
            }
        }

        console.error('未找到管理员行，ID: ' + id);
    }

    // 关闭删除确认模态框
    function closeDeleteModal() {
        currentAdminId = null;
        document.getElementById('deleteModal').classList.add('hidden');
    }

    // 确认删除管理员
    function confirmDeleteAdmin() {
        if (currentAdminId) {
            // 使用表单提交进行删除
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '<%= request.getContextPath() %>/cjj/manage_admins.jsp';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'delete';

            const adminIdInput = document.createElement('input');
            adminIdInput.type = 'hidden';
            adminIdInput.name = 'id';
            adminIdInput.value = currentAdminId;

            form.appendChild(actionInput);
            form.appendChild(adminIdInput);
            document.body.appendChild(form);

            // 提交表单前添加确认提示
            if (confirm('确定要删除这个管理员账户吗？此操作不可撤销。')) {
                form.submit();
            }

            // 移除临时表单
            document.body.removeChild(form);
        }
        closeDeleteModal();
    }

    // 关闭添加模态框
    function closeAddModal() {
        document.getElementById('addAdminModal').classList.add('hidden');
    }

    // 显示通知
    function showNotification(type, message) {
        const notification = document.createElement('div');
        notification.className = `fixed top-20 left-1/2 transform -translate-x-1/2 px-4 py-3 rounded-lg z-50 flex items-center ${type == 'success' ? 'bg-green-50 border border-green-200 text-green-700' : 'bg-red-50 border border-red-200 text-red-700'} shadow-lg`;
        notification.innerHTML = `
            <i class="fa fa-${type == 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
            <span>${message}</span>
        `;
        document.body.appendChild(notification);

        // 3秒后隐藏通知
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translate(-50%, -20px)';
            notification.style.transition = 'all 0.3s ease';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
</script>
</body>
</html>